﻿Imports System.Xml.Serialization

Public Class Serialization
    Public Shared Function ToXml(Of T)(ByVal [object] As T) As String
        Using clsTW As New System.IO.StringWriter
            Dim clsX As New System.Xml.Serialization.XmlSerializer(GetType(T))
            clsX.Serialize(clsTW, [object])
            Return clsTW.GetStringBuilder.ToString
        End Using
    End Function
    Public Shared Function ToXmlBytes(Of T)(ByVal [object] As T) As Byte()
        Using clsTW As New System.IO.StringWriter
            Dim clsX As New System.Xml.Serialization.XmlSerializer(GetType(T))
            clsX.Serialize(clsTW, [object])
            Return System.Text.Encoding.UTF8.GetBytes(clsTW.GetStringBuilder.ToString)
        End Using
    End Function
    Public Shared Function FromXml(Of T)(ByVal xml As String) As T
        Using clsTR As New System.IO.StringReader(xml)
            Dim clsX As New System.Xml.Serialization.XmlSerializer(GetType(T))
            Return CType(clsX.Deserialize(clsTR), T)
        End Using
    End Function
    Public Shared Function FromXmlBytes(Of T)(ByVal xml() As Byte) As T
        Using clsTR As New System.IO.StringReader(System.Text.Encoding.UTF8.GetString(xml))
            Dim clsX As New System.Xml.Serialization.XmlSerializer(GetType(T))
            Return CType(clsX.Deserialize(clsTR), T)
        End Using
    End Function

    Public Shared Function ToCommaSepString(ByVal list As Generic.List(Of String)) As String
        If list Is Nothing Then Return Nothing
        If list.Count = 0 Then Return Nothing
        Dim clsSB As New System.Text.StringBuilder
        For Each strItem As String In list
            If clsSB.Length > 0 Then clsSB.Append(","c)
            clsSB.Append(strItem)
        Next
        Return clsSB.ToString
    End Function
    Public Shared Function FromCommaSepString(ByVal text As String) As Generic.List(Of String)
        If text Is Nothing Then Return Nothing

        Dim aItems() As String = text.Split(","c)
        Dim aRet As New Generic.List(Of String)
        For Each strItem As String In aItems
            aRet.Add(strItem)
        Next
        Return aRet
    End Function


End Class
